<template>
  <div>
    <vxe-grid ref="xGrid" v-bind="gridOptions" row-id="id" height="500">
      <template #toolbar_buttons>
        <vxe-button @click="onAdd()">新增一级节点</vxe-button>
        <vxe-button @click="onChildAdd">新增子节点</vxe-button>
      </template>
      <template #operate="{ row }">
        <vxe-button size="small" content="编辑" @click="onEdit(row)"></vxe-button>
        <vxe-button size="small" content="删除" @click="onRemove(row)"></vxe-button>
        <vxe-button size="small" content="查看" @click="onDetails(row)"></vxe-button>
      </template>
    </vxe-grid>
  </div>
</template>
<script>
// import XEUtils from 'xe-utils'
export default {
  name: 'PermissionInfo',
  data () {
    return {
      gridOptions: {
        border: true,
        showOverflow: true,
        resizable: true,
        keepSource: true,
        highlightCurrentRow: true,
        toolbarConfig: {
          slots: {
            buttons: 'toolbar_buttons'
          }
        },
        checkboxConfig: {
          highlight: true
        },
        treeConfig: {
          lazy: true,
          reserve: true,
          children: 'children',
          hasChild: 'leaf', // 设置是否有子节点标识，0为false，1为true
          loadMethod: ({ row }) => {
            return new Promise((resolve, reject) => {
              resolve(this.getData(row))
            })
          }
        },
        proxyConfig: {
          ajax: {
            query: () => {
              return new Promise(resolve => {
                setTimeout(() => {
                  resolve(this.getData())
                }, 500)
              })
            }
          }
        },
        columns: [
          // { type: 'checkbox', width: 50 },
          { field: 'permsName', title: '资源名称', treeNode: true, width: 250 },
          { field: 'permsType', title: '资源类型', formatter: ({ row }) => { return this.formatterType(row) }, width: 80 },
          { field: 'url', title: '访问路径', width: 250 },
          { field: 'component', title: '前端页面路径', width: 230 },
          {
            title: '状态',
            field: 'validation',
            formatter: ({ row }) => {
              return this.$c.dictCode.validation.find(i => i.value === row.validation).label
            },
            width: 50
          },
          { field: 'sortNo', title: '排序', width: 50 },
          { title: '操作', width: 220, slots: { default: 'operate' } }
        ]
      },
      fApi: null,
      rule: [
        { type: 'Hidden', field: 'id' },
        { type: 'Hidden', field: 'parentId' },
        {
          type: 'Radio',
          title: '资源类型',
          field: 'permsType',
          on: {
            change: (e) => {
              // alert(e + `change!!"${this.fApi.getValue('permsType')}"`)
              const val = `${this.fApi.getValue('permsType')}`
              this.handleDisplay(val)
            }
          }
        },
        { type: 'Input', title: '资源名称', field: 'permsName', validate: [this.$v.required(), this.$v.maxLength(50)] },
        { type: 'Input', title: '父节点名称', field: 'parentName' },
        { type: 'Input', title: '访问路径', field: 'url', validate: [this.$v.maxLength(100)] },
        // { type: 'OpUpload', title: '图', field: 'icon', col: { span: 24 }, props: {dir: 'house', object: true} },
        { type: 'Input', title: '前端页面路径', field: 'component', validate: [this.$v.maxLength(100)] },
        {
          type: 'Radio',
          title: '请求类型',
          field: 'requestType',
          on: {
            change: (e) => {
              this.fApi.setValue({ isCheckRequestType: '1' })
            }
          }
        },
        {
          type: 'Radio',
          title: '是否检验请求类型',
          field: 'isCheckRequestType'
        },
        { type: 'Input', title: '授权标识', field: 'permsCode' },
        { type: 'Input', title: 'Icon', field: 'icon' },
        { type: 'Input', title: '排序', field: 'sortNo' },
        { type: 'Radio', title: '是否有效', field: 'validation' }
      ],
      ruleDetails: [
        { type: 'Input', title: '资源类型', field: 'permsType' },
        { type: 'Input', title: '资源名称', field: 'permsName' },
        { type: 'Input', title: '父节点名称', field: 'parentName' },
        { type: 'Input', title: '访问路径', field: 'url' },
        { type: 'Input', title: '前端页面路径', field: 'component' },
        { type: 'Input', title: '请求类型', field: 'requestType' },
        { type: 'Input', title: '是否检验请求类型', field: 'isCheckRequestType' },
        { type: 'Input', title: '授权标识', field: 'permsCode' },
        { type: 'Input', title: 'Icon', field: 'icon' },
        { type: 'Input', title: '排序', field: 'sortNo' },
        { type: 'Input', title: '是否有效', field: 'validation' }
      ],
      options: {
        ...this.$utils.formOptions(140, 24),
        mounted: $f => {
          this.$utils.updateFormOptions($f, 'permsType', this.$c.dictCode.permsType)
          this.$utils.updateFormOptions($f, 'isCheckRequestType', this.$c.dictCode.validation)
          this.$utils.updateFormOptions($f, 'validation', this.$c.dictCode.validation)
          this.$utils.updateFormOptions($f, 'requestType', this.$c.dictCode.requestType)
        }
      }
    }
  },
  mounted () {
  },
  methods: {
    // 获取数据
    async getData (row) {
      let parentId = '-1'; let parentName = ''
      if (row) {
        parentId = row.id
        parentName = row.permsName
      }
      // const data = axios({ url: 'system/getPermListByParentId', method: 'get', data: parameter })
      const { data } = await this.$store.dispatch('system/getPermListByParentId', { parentId, parentName })
      return data
    },
    onAdd (row) {
      this.handleData(row)
    },
    onChildAdd () {
      const row = this.$refs.xGrid.getCurrentRecord()
      if (!row) {
        this.$utils.alert('请选择父节点！')
        return
      }
      this.onAdd({ parentId: row.id, parentName: row.permsName, permsType: '1', validation: '1' })
    },
    onEdit (row) {
      this.handleData(row)
    },
    handleData (row) {
      const btn = [{ text: '保存', loading: true, cb: cb => this.save(cb, row) }]
      const o = {}
      for (const item of this.rule) {
        o[item.field] = null
      }
      this.$utils.dialog(`${row?.id ? '编辑' : '添加'}资源`, <form-create vModel={this.fApi} rule={this.rule} option={this.options} />, { btn, width: '60%' })
      this.$nextTick(() => {
        if (row && row.id) { // 修改
          this.fApi.setValue(row)
        } else {
          this.fApi.setValue(o)
          if (!row) row = { parentId: '-1', permsType: '0', validation: '1' } // 新增一级节点
          this.fApi.setValue(row) // 设置值
        }
        this.handleDisplay(row.permsType)
        this.fApi.disabled(true, 'parentName')
      })
    },
    save (cb, row) {
      this.fApi.validate(async (valid) => {
        cb()
        if (valid) {
          const formData = this.fApi.formData()
          // console.info('-----------formData: ' + JSON.stringify(formData))
          const action = row.id ? 'system/permsUpdate' : 'system/permsInsert'
          const { error } = await this.$store.dispatch(action, formData)

          if (!error) {
            this.$utils.message.success('保存成功！')
            this.$utils.hideDialog()
            this.refresh()
          } else {
            this.$utils.message.error(error.message)
          }
        }
      })
    },
    onClose (cb) {
      this.$utils.hideDialog()
    },
    onRemove (row) {
      this.$utils.confirm('您确定要删除该数据?').then(type => {
        const $grid = this.$refs.xGrid
        if (type) {
          const row = $grid.getCurrentRecord()
          const { error } = this.$store.dispatch('system/permsDelete', row.id)
          if (!error) {
            this.$utils.message.success('删除成功！')
            this.refresh()
          } else {
            this.$utils.message.error(error.message)
          }
        }
      })
    },
    onDetails (row) {
      const btn = [{ text: '关闭', loading: true, cb: this.onClose }]
      this.$utils.dialog('资源详细', <form-create vModel={this.fApi} rule={this.ruleDetails} option={this.options} />, { btn, width: '70%' })
      this.$nextTick(() => {
        this.fApi.setValue(row)
        this.fApi.setValue({ permsType: this.formatterType(row), requestType: this.formatterRequestType(row), isCheckRequestType: this.formatterValild(row), validation: this.formatterValild(row) })
        this.fApi.disabled(true, this.fApi.fields())
        this.fApi.hidden(false, this.fApi.fields())
        if (row.permsType === '0') {
          this.fApi.hidden(true, ['parentName', 'requestType', 'isCheckRequestType', 'permsCode'])
        } else if (row.permsType === '1') {
          this.fApi.hidden(true, ['requestType', 'isCheckRequestType', 'permsCode'])
        } else if (row.permsType === '2' || row.permsType === '3') {
          this.fApi.hidden(true, ['component', 'icon'])
        }
      })
    },
    handleDisplay (val) {
      if (val === '0') {
        this.fApi.display(false, ['permsType', 'parentName', 'requestType', 'isCheckRequestType', 'permsCode'])
        this.fApi.display(true, ['component', 'icon'])
      } else if (val === '1') {
        this.fApi.display(false, ['requestType', 'isCheckRequestType', 'permsCode'])
        this.fApi.display(true, ['permsType', 'parentName', 'component', 'icon'])
        this.fApi.disabled(true, 'parentName')
      } else if (val === '2' || val === '3') {
        this.fApi.display(false, ['component', 'icon'])
        this.fApi.display(true, ['permsType', 'parentName', 'requestType', 'isCheckRequestType', 'permsCode'])
        this.fApi.disabled(true, 'parentName')
      }
    },
    refresh () {
      // 新增/修改 成功时，重载列表
      // 刷新表格,对应 ajax: {query}
      this.$refs.xGrid.commitProxy('query')
    },
    formatterType (row) {
      const permsTypeList = [{ value: '0', label: '一级菜单' }, ...this.$c.dictCode.permsType]
      const item = permsTypeList.find(item => item.value === row.permsType)
      return item ? item.label : ''
    },
    formatterRequestType (row) {
      const item = this.$c.dictCode.requestType.find(item => item.value === row.requestType)
      return item ? item.label : ''
    },
    formatterValild (row) {
      const item = this.$c.dictCode.validation.find(item => item.value === row.validation)
      return item ? item.label : ''
    }
  }
}
</script>
